package com.agilegroup.crm.ui.fragments;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.agilegroup.crm.utils.OnlineChecker;

/**
 * @author Hisham
 *
 */
public class CustomTabListener<T extends Fragment> implements TabListener {
    private Fragment mFragment;
    private final SherlockFragmentActivity mActivity;
    private final String mTag;
    private final Class<T> mClass;
 
    public CustomTabListener(SherlockFragmentActivity activity, String tag, Class<T> clz){
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }
 
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // Nothing special to do here for this application
    }
 
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
    	OnlineChecker checker = new OnlineChecker(mActivity);
        if(checker.isOnline()==true){
        	mFragment = mActivity.getSupportFragmentManager().findFragmentByTag(mTag);
            if(mFragment==null){
                mFragment = Fragment.instantiate(mActivity, mClass.getName());
                ft.add(android.R.id.content,mFragment, mTag);
            }else{
                ft.attach(mFragment);
            }
        }
        else{
        	SherlockDialogFragment dialogFragment = new ConnectionDialogFragment();
			dialogFragment.show(mActivity.getSupportFragmentManager(), "connectionDialog");
//    		AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
//    		builder.setMessage("Sorry,you have to be online")
//    		.setCancelable(false)
//  	        .setPositiveButton("OK", new DialogInterface.OnClickListener(){
//
//				@Override
//				public void onClick(DialogInterface dialog, int which) {
//					mActivity.finish();
//				}
//  	        	
//  	        })
//  	        .setTitle("ERROR")
//  	        .show();
    	}
        
    }
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if(mFragment!=null) {
            ft.detach(mFragment);
        }
    }
}